package com.qianlima.upload.infrastructure.db.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qianlima.upload.common.dto.FileDto;
import com.qianlima.upload.domain.repository.IFileRepository;
import com.qianlima.upload.infrastructure.db.mapper.FileMapper;
import com.qianlima.upload.infrastructure.db.po.FilePo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * @description: 文件仓储实现层
 * @author：allms
 * @date: 2023/3/22 18:16
 */
@Repository
public class FileRepository implements IFileRepository {

    @Resource
    private FileMapper fileMapper;

    @Override
    public FileDto findFileByKey(String key) {
        LambdaQueryWrapper<FilePo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FilePo::getFileKey, key);
        FilePo filePo = fileMapper.selectOne(queryWrapper);
        if (filePo == null) {
            return null;
        }
        FileDto fileDto = new FileDto();
        BeanUtils.copyProperties(filePo, fileDto);
        return fileDto;
    }

    @Override
    public boolean saveFile(FileDto fileDto) {
        FilePo filePo = new FilePo();
        BeanUtils.copyProperties(fileDto, filePo);
        filePo.setShardIndex(1);
        int insert = fileMapper.insert(filePo);
        return insert > 0;
    }

    @Override
    public boolean updateFile(String key, Integer lastIndex) {
        FilePo filePo = new FilePo();
        LambdaUpdateWrapper<FilePo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Objects.nonNull(key), FilePo::getFileKey, key)
                .set(FilePo::getShardIndex, lastIndex + 1)
                .set(FilePo::getUpdateTime, new Date());
        filePo.setFileKey(key);
        int i = fileMapper.update(filePo, lambdaUpdateWrapper);
        return i == 1;
    }

}
